package com.czuft.usersystem.controller;
import com.czuft.usersystem.config.MyWebAppConfigurer;
import com.czuft.usersystem.dao.Result;
import com.czuft.usersystem.pojo.User;
import com.czuft.usersystem.service.FileService;
import com.czuft.usersystem.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
/**
 * 文件上传
 */
@Controller
@RequestMapping({"/file"})
public class FileController {

    @Resource()
    private FileService fileService;

    @Resource()
    private UserService userService;

    @Resource()
    private MyWebAppConfigurer config;

    @PostMapping(value = "/fileUpload")
    @ResponseBody
    public Result fileUpload( User user, HttpServletRequest req) throws Exception {
        String filename = fileService.upLoadFile(req);
        Result result = new Result();
        if (filename.equals("")) {
            result.setResult("error");
            result.setMessage("上传失败");
        } else {
            result.setResult("success");
            result.setMessage("上传完成");
        }
        if (user != null && user.getName() != null && !user.getName().equals("")) {
            User tuser = userService.getUserByName(user);
            // 删除原来的图片
            if (tuser.getUserimg() != null
                    && !(tuser.getUserimg().equals(""))
                    && !(filename.equals(tuser.getUserimg()))) {
                String filePath = config.ROOT_PATH + tuser.getUserimg().replace("/upload/", "");
                fileService.deleteFile(filePath);
            }
            tuser.setUserimg(filename);
            userService.update(tuser);
        }
        result.setImgUrl(filename);
        return result;
    }
}